/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function (root, p, q) {
  // 如果当前节点为空，或者等于p、q中的一个，直接返回当前节点
  if (root === null || root === p || root === q) {
    return root;
  }

  // 递归检查左子树
  const left = lowestCommonAncestor(root.left, p, q);
  // 递归检查右子树
  const right = lowestCommonAncestor(root.right, p, q);

  // 如果左右子树均找到p和q，则当前节点是LCA
  if (left !== null && right !== null) {
    return root;
  }

  // 否则，返回非空的子树结果
  return left !== null ? left : right;
};